﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Text;
using System.EnterpriseServices;
using System.Configuration;
using System.Xml;
using App.SendMessage;
using Models;
using Common;
using Langben.DAL;
using Langben.BLL;
using Langben.App.Models;

namespace Langben.App.Controllers
{
    /// <summary>
    /// Message
    /// </summary>
    public class MessageController : BaseController
    {

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Index()
        {
        
            return View();
        }

        [SupportFilter]
        public ActionResult SendMessage()
        {
        
            return View();
        }
         
        /// <summary>
        /// 异步加载数据
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">每页显示的行数</param>
        /// <param name="order">排序字段</param>
        /// <param name="sort">升序asc（默认）还是降序desc</param>
        /// <param name="search">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetData(string id, int page, int rows, string order, string sort, string search)
        {

            int total = 0;
            List<Message> queryData = m_BLL.GetByParam(id, page, rows, order, sort, search, ref total);
            return Json(new datagrid
            {
                total = total,
                rows = queryData.Select(s => new
                {
                    RowGuid = s.RowGuid
					,CreateTime = s.CreateTime
					,CreatePerson = s.CreatePerson
					,Content = s.Content
					,State = s.State
                    ,
                    SuccessCount = s.SuccessCount
                    ,
                    FaildCount = s.FaildCount
                    ,
                    UserName = s.UserName
                    ,
                    PayCount = s.PayCount
                    ,
                    Type = s.Type
                   ,
                    TelNo = s.TelNo
					
                }

                    )
            });
        }
        /// <summary>
        ///  导出Excle /*在6.0版本中 新增*/
        /// </summary>
        /// <param name="param">Flexigrid传过到后台的参数</param>
        /// <returns></returns>      
        [HttpPost]
        public ActionResult Export(string id, string title, string field, string sortName, string sortOrder, string search)
        {
            string[] titles = title.Split(',');//如果确定显示的名称，可以直接定义
            string[] fields = field.Split(',');
            List<Message> queryData = m_BLL.GetByParam(id, sortOrder, sortName, search);
             
            return Content(WriteExcle(titles, fields, queryData.ToArray()));  
        }
        /// <summary>
        /// 查看详细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [SupportFilter]  
        public ActionResult Details(string id)
        {
            Message item = m_BLL.GetById(id);
            return View(item);

        }
 
        /// <summary>
        /// 首次创建
        /// </summary>
        /// <returns></returns>
        [SupportFilter]
        public ActionResult Create(string id)
        { 
            
            return View();
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Create(Message entity)
        {           
            if (entity != null && ModelState.IsValid)
            {
                string currentPerson = GetCurrentPerson();
                entity.CreateTime = DateTime.Now;
                entity.CreatePerson = currentPerson;
              
                entity.RowGuid = Result.GetNewId();   
                string returnValue = string.Empty;
                if (m_BLL.Create(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.InsertSucceed  + "，Message的信息的Id为" + entity.RowGuid,"Message"
                        );//写入日志 
                    return Json(Suggestion.InsertSucceed);
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.InsertFail + "，Message的信息，" + returnValue,"Message"
                        );//写入日志                      
                    return Json(Suggestion.InsertFail  + returnValue); //提示插入失败
                }
            }

            return Json(Suggestion.InsertFail + "，请核对输入的数据的格式"); //提示输入的数据的格式不对 
        }
        /// <summary>
        /// 首次编辑
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns> 
        [SupportFilter] 
        public ActionResult Edit(string id)
        {
            Message item = m_BLL.GetById(id);
            return View(item);
        }
        /// <summary>
        /// 提交编辑信息
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="collection">客户端传回的集合</param>
        /// <returns></returns>
        [HttpPost]
        [SupportFilter]
        public ActionResult Edit(string id, Message entity)
        {
            if (entity != null && ModelState.IsValid)
            {   //数据校验
            
                string currentPerson = GetCurrentPerson();                 
                //entity.UpdateTime = DateTime.Now;
                //entity.UpdatePerson = currentPerson;
                           
                string returnValue = string.Empty;   
                if (m_BLL.Edit(ref validationErrors, entity))
                {
                    LogClassModels.WriteServiceLog(Suggestion.UpdateSucceed + "，Message信息的Id为" + id,"Message"
                        );//写入日志                           
                    return Json(Suggestion.UpdateSucceed); //提示更新成功 
                }
                else
                { 
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.UpdateFail + "，Message信息的Id为" + id + "," + returnValue, "Message"
                        );//写入日志                           
                    return Json(Suggestion.UpdateFail  + returnValue); //提示更新失败
                }
            }
            return Json(Suggestion.UpdateFail + "请核对输入的数据的格式"); //提示输入的数据的格式不对               
          
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>   
        [HttpPost]
        public ActionResult Delete(FormCollection collection)
        {
            string returnValue = string.Empty;
            string[] deleteId = collection["query"].GetString().Split(',');
            if (deleteId != null && deleteId.Length > 0)
            { 
                if (m_BLL.DeleteCollection(ref validationErrors, deleteId))
                {
                    LogClassModels.WriteServiceLog(Suggestion.DeleteSucceed + "，信息的Id为" + string.Join(",", deleteId), "消息"
                        );//删除成功，写入日志
                    return Json("OK");
                }
                else
                {
                    if (validationErrors != null && validationErrors.Count > 0)
                    {
                        validationErrors.All(a =>
                        {
                            returnValue += a.ErrorMessage;
                            return true;
                        });
                    }
                    LogClassModels.WriteServiceLog(Suggestion.DeleteFail + "，信息的Id为" + string.Join(",", deleteId)+ "," + returnValue, "消息"
                        );//删除失败，写入日志
                }
            }
            return Json(returnValue);
        }
     
        IBLL.IMessageBLL m_BLL;

        ValidationErrors validationErrors = new ValidationErrors();

        public MessageController()
            : this(new MessageBLL()) { }

        public MessageController(MessageBLL bll)
        {
            m_BLL = bll;
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="geren">个人通讯录userguid</param>
        /// <param name="xitong">系统personguid</param>
        /// <param name="content">内容</param>
        /// <returns></returns>
        public string AjaxSendMessage(string geren, string xitong, string content)
        {
            int messagecount = 0;
            string[] gerenguidlist = {};
            string gerentelstr = string.Empty;
            string namelist = string.Empty;
            if (!string.IsNullOrEmpty(geren))
            {
                gerenguidlist = geren.Split(',');
                foreach (var gerenguid in gerenguidlist)
                {
                    //不为空的时候
                    if (!string.IsNullOrEmpty(gerenguid))
                    {
                        TelList tellist = new TelList();
                        tellist = new TelListBLL().GetById(gerenguid);
                        if (!string.IsNullOrEmpty(gerentelstr))
                        {
                            gerentelstr += ",";
                        }
                        gerentelstr += tellist.Tel;
                        if (!string.IsNullOrEmpty(namelist))
                        {
                            namelist += ",";
                        }
                        namelist += tellist.Name;
                        messagecount++;
                    }
                }
            }


            string[] xitongguidlist = {};
            string xitongtelstr = string.Empty;
            if (!string.IsNullOrEmpty(xitong))
            {
                xitongguidlist = xitong.Split(',');
                foreach (var xitongguid in xitongguidlist)
                {
                    //不为空的时候
                    if (!string.IsNullOrEmpty(xitongguid))
                    {
                        SysPerson sysPerson = new SysPerson();
                        sysPerson = new SysPersonBLL().GetById(xitongguid);
                        if (!string.IsNullOrEmpty(xitongtelstr))
                        {
                            xitongtelstr += ",";
                        }
                        xitongtelstr += sysPerson.MobilePhoneNumber;
                        if (!string.IsNullOrEmpty(namelist))
                        {
                            namelist += ",";
                        }
                        namelist += sysPerson.Name;
                        messagecount++;
                    }
                }
            }
            if (!string.IsNullOrEmpty(gerentelstr) && !string.IsNullOrEmpty(xitongtelstr))
            {
                gerentelstr += ",";
            }
            string telnolist = gerentelstr + xitongtelstr;
            SmsServiceSoapClient sms = new SmsServiceSoapClient();
            XmlNode beitoushuNode = sms.SendEx("chonglang", "757783e6cf17b26f", "808", telnolist, "",
                            content + "【政务服务中心】");

            Message message=new Message();

            message.RowGuid = Convert.ToString(Guid.NewGuid());
            message.TelNo = telnolist;
            message.State = beitoushuNode.InnerXml;
            message.CreateTime = DateTime.Now;
            message.Content = content+"【政务服务中心】";
            message.CreatePerson=  GetCurrentPerson();
            message.UserName = namelist;
            //初始化一下
            message.SuccessCount = 0;
            try
            {
                message.SuccessCount = Convert.ToInt32(beitoushuNode.SelectSingleNode("/SuccessCount").InnerText);
            }
            catch (Exception ex)
            {
                
            }
            try
            {
                message.FaildCount = Convert.ToInt32(beitoushuNode.SelectSingleNode("/FailCount").InnerText);
            }
            catch (Exception ex)
            {

            }
            try
            {
                message.PayCount = Convert.ToInt32(beitoushuNode.SelectSingleNode("/PayCount").InnerText);
            }
            catch (Exception ex)
            {

            }
            message.Type = "短信平台";
            new MessageBLL().Create(ref validationErrors, message);



            if (messagecount == message.SuccessCount)
            {
                return "发送成功。";
            }
            else
            {
                return "发送有问题，请联系管理员。";
            }
            
            
        }

    }
}


